import cloud from '@lafjs/cloud'
let data
const db = cloud.mongo.db

export default async function (ctx: FunctionContext) {
  if (ctx.body.data) data = cloud.utils.deepcopy(ctx.body.data) //入参

  console.log("ctx.body.type", ctx.body.type)
  switch (ctx.body.type) {
    case "list":
      return list()
      break;
    case "bindTag":
      return bindTag()
      break;
    case "bindIndexMax":
      return bindIndexMax()
      break;
    case "query":
      return query()
      break;
    default:
      break;
  }
}

async function query() {
  let res = await db.collection("admin-train-tag").find({}).toArray()
  return cloud.utils.requestReturn({ data: res })
}

async function bindIndexMax() {
  let current = 0
  let array = await db.collection("admin-train-tag").find({}).toArray()
  array.forEach(element => {
    if (element.index) {
      let num = Number(element.index)
      if (num > current) current = num
    }
  });
  return cloud.utils.requestReturn({ data: current })
}

async function bindTag() {
  await cloud.utils.deleteData("admin-train-tag", { trainId: data.trainId })
  await cloud.nw.db.add({
    dbName: "admin-train-tag",
    dataJson: data,
    cancelAddTime: false
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function list() {
  let res = await cloud.nw.db.selects({
    dbName: "moxueyuan-train",
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    // 主表 where 条件
    whereJson: {
      startTime: { $regex: data.year.toString(), $options: "i" },
      archive: "N",
      delete: "N"
    },
    // 主表字段显示规则
    fieldJson: {
      contentList: false,
    },
    // 主表排序规则
    sortArr: [{ "name": "startTime", "type": "desc" }],
    // 副表列表
    foreignDB: [
      {
        dbName: "admin-train-tag",//副表 vip
        localKey: "trainId",
        foreignKey: "trainId",
        as: "tagInfo",
        limit: 1,
      }
    ]
  });
  return cloud.utils.requestReturn({ data: res })
}
